package com.sg.zhui.visitor.utils;

import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.CharacterStyle;
import android.text.style.ForegroundColorSpan;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.TimeZone;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串工具类
 * 
 * @author lmm
 * 
 */
public class StringUtil {

	private final static Pattern emailer = Pattern
			.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");

	private final static Pattern IMG_URL = Pattern
			.compile(".*?(gif|jpeg|png|jpg|bmp)");

	private final static Pattern URL = Pattern
			.compile("^(https|http)://.*?$(net|com|.com.cn|org|me|)");

	private final static ThreadLocal<SimpleDateFormat> dateFormater = new ThreadLocal<SimpleDateFormat>() {
		@Override
		protected SimpleDateFormat initialValue() {
			return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		}
	};

	private final static ThreadLocal<SimpleDateFormat> dateFormater2 = new ThreadLocal<SimpleDateFormat>() {
		@Override
		protected SimpleDateFormat initialValue() {
			return new SimpleDateFormat("yyyy-MM-dd");
		}
	};

	/**
	 * 将字符串转位日期类型
	 *
	 * @param sdate
	 * @return
	 */
	public static Date toDate(String sdate) {
		return toDate(sdate, dateFormater.get());
	}

	public static Date toDate(String sdate, SimpleDateFormat dateFormater) {
		try {
			return dateFormater.parse(sdate);
		} catch (ParseException e) {
			return null;
		}
	}

	public static String getDateString(Date date) {
		return dateFormater.get().format(date);
	}

	/**
	 * 以友好的方式显示时间
	 *
	 * @param sdate
	 * @return
	 */

	public static String friendly_time2(String sdate) {
		String res = "";
		if (isEmpty(sdate))
			return "";

		String[] weekDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
		String currentData = getDataTime("MM-dd");
		int currentDay = toInt(currentData.substring(3));
		int currentMoth = toInt(currentData.substring(0, 2));

		int sMoth = toInt(sdate.substring(5, 7));
		int sDay = toInt(sdate.substring(8, 10));
		int sYear = toInt(sdate.substring(0, 4));
		Date dt = new Date(sYear, sMoth - 1, sDay - 1);

		if (sDay == currentDay && sMoth == currentMoth) {
			res = "今天 / " + weekDays[getWeekOfDate(new Date())];
		} else if (sDay == currentDay + 1 && sMoth == currentMoth) {
			res = "昨天 / " + weekDays[(getWeekOfDate(new Date()) + 6) % 7];
		} else {
			if (sMoth < 10) {
				res = "0";
			}
			res += sMoth + "/";
			if (sDay < 10) {
				res += "0";
			}
			res += sDay + " / " + weekDays[getWeekOfDate(dt)];
		}

		return res;
	}


	/**
	 * 智能格式化
	 */
	public static String friendly_time3(String sdate) {
		String res = "";
		if (isEmpty(sdate))
			return "";

		Date date = toDate(sdate);
		if (date == null)
			return sdate;

		SimpleDateFormat format = dateFormater2.get();

		if (isToday(date.getTime())) {
			format.applyPattern(isMorning(date.getTime()) ? "上午 hh:mm" : "下午 hh:mm");
			res = format.format(date);
		} else if (isYesterday(date.getTime())) {
			format.applyPattern(isMorning(date.getTime()) ? "昨天 上午 hh:mm" : "昨天 下午 hh:mm");
			res = format.format(date);
		} else if (isCurrentYear(date.getTime())) {
			format.applyPattern(isMorning(date.getTime()) ? "MM-dd 上午 hh:mm" : "MM-dd 下午 hh:mm");
			res = format.format(date);
		} else {
			format.applyPattern(isMorning(date.getTime()) ? "yyyy-MM-dd 上午 hh:mm" : "yyyy-MM-dd 下午 hh:mm");
			res = format.format(date);
		}
		return res;
	}

	/**
	 * @return 判断一个时间是不是上午
	 */
	public static boolean isMorning(long when) {
		android.text.format.Time time = new android.text.format.Time();
		time.set(when);

		int hour = time.hour;
		return (hour >= 0) && (hour < 12);
	}

	/**
	 * @return 判断一个时间是不是今天
	 */
	public static boolean isToday(long when) {
		android.text.format.Time time = new android.text.format.Time();
		time.set(when);

		int thenYear = time.year;
		int thenMonth = time.month;
		int thenMonthDay = time.monthDay;

		time.set(System.currentTimeMillis());
		return (thenYear == time.year)
				&& (thenMonth == time.month)
				&& (thenMonthDay == time.monthDay);
	}

	/**
	 * @return 判断一个时间是不是昨天
	 */
	public static boolean isYesterday(long when) {
		android.text.format.Time time = new android.text.format.Time();
		time.set(when);

		int thenYear = time.year;
		int thenMonth = time.month;
		int thenMonthDay = time.monthDay;

		time.set(System.currentTimeMillis());
		return (thenYear == time.year)
				&& (thenMonth == time.month)
				&& (time.monthDay - thenMonthDay == 1);
	}

	/**
	 * @return 判断一个时间是不是今年
	 */
	public static boolean isCurrentYear(long when) {
		android.text.format.Time time = new android.text.format.Time();
		time.set(when);

		int thenYear = time.year;

		time.set(System.currentTimeMillis());
		return (thenYear == time.year);
	}

	/**
	 * 获取当前日期是星期几<br>
	 *
	 * @param dt
	 * @return 当前日期是星期几
	 */
	public static int getWeekOfDate(Date dt) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(dt);
		int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
		if (w < 0)
			w = 0;
		return w;
	}

	/**
	 * 判断给定字符串时间是否为今日
	 *
	 * @param sdate
	 * @return boolean
	 */
	public static boolean isToday(String sdate) {
		boolean b = false;
		Date time = toDate(sdate);
		Date today = new Date();
		if (time != null) {
			String nowDate = dateFormater2.get().format(today);
			String timeDate = dateFormater2.get().format(time);
			if (nowDate.equals(timeDate)) {
				b = true;
			}
		}
		return b;
	}

	/**
	 * 返回long类型的今天的日期
	 *
	 * @return
	 */
	public static long getToday() {
		Calendar cal = Calendar.getInstance();
		String curDate = dateFormater2.get().format(cal.getTime());
		curDate = curDate.replace("-", "");
		return Long.parseLong(curDate);
	}

	public static String getCurTimeStr() {
		Calendar cal = Calendar.getInstance();
		String curDate = dateFormater.get().format(cal.getTime());
		return curDate;
	}

	/***
	 * 计算两个时间差，返回的是的秒s
	 *
	 * @author 火蚁 2015-2-9 下午4:50:06
	 *
	 * @return long
	 * @param dete1
	 * @param date2
	 * @return
	 */
	public static long calDateDifferent(String dete1, String date2) {

		long diff = 0;

		Date d1 = null;
		Date d2 = null;

		try {
			d1 = dateFormater.get().parse(dete1);
			d2 = dateFormater.get().parse(date2);

			// 毫秒ms
			diff = d2.getTime() - d1.getTime();

		} catch (Exception e) {
			e.printStackTrace();
		}

		return diff / 1000;
	}

	/**
	 * 判断给定字符串是否空白串。 空白串是指由空格、制表符、回车符、换行符组成的字符串 若输入字符串为null或空字符串，返回true
	 *
	 * @param input
	 * @return boolean
	 */
	public static boolean isEmpty(String input) {
		if (input == null || "".equals(input))
			return true;

		for (int i = 0; i < input.length(); i++) {
			char c = input.charAt(i);
			if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
				return false;
			}
		}
		return true;
	}

	/**
	 * 判断是不是一个合法的电子邮件地址
	 *
	 * @param email
	 * @return
	 */
	public static boolean isEmail(String email) {
		if (email == null || email.trim().length() == 0)
			return false;
		return emailer.matcher(email).matches();
	}

	/**
	 * 判断一个url是否为图片url
	 *
	 * @param url
	 * @return
	 */
	public static boolean isImgUrl(String url) {
		if (url == null || url.trim().length() == 0)
			return false;
		return IMG_URL.matcher(url).matches();
	}

	/**
	 * 判断是否为一个合法的url地址
	 *
	 * @param str
	 * @return
	 */
	public static boolean isUrl(String str) {
		if (str == null || str.trim().length() == 0)
			return false;
		return URL.matcher(str).matches();
	}

	/**
	 * 字符串转整数
	 *
	 * @param str
	 * @param defValue
	 * @return
	 */
	public static int toInt(String str, int defValue) {
		try {
			return Integer.parseInt(str);
		} catch (Exception e) {
		}
		return defValue;
	}

	/**
	 * 对象转整数
	 *
	 * @param obj
	 * @return 转换异常返回 0
	 */
	public static int toInt(Object obj) {
		if (obj == null)
			return 0;
		return toInt(obj.toString(), 0);
	}

	/**
	 * 对象转整数
	 *
	 * @param obj
	 * @return 转换异常返回 0
	 */
	public static long toLong(String obj) {
		try {
			return Long.parseLong(obj);
		} catch (Exception e) {
		}
		return 0;
	}

	/**
	 * 字符串转布尔值
	 *
	 * @param b
	 * @return 转换异常返回 false
	 */
	public static boolean toBool(String b) {
		try {
			return Boolean.parseBoolean(b);
		} catch (Exception e) {
		}
		return false;
	}

	public static String getString(String s) {
		return s == null ? "" : s;
	}

	/**
	 * 将一个InputStream流转换成字符串
	 *
	 * @param is
	 * @return
	 */
	public static String toConvertString(InputStream is) {
		StringBuffer res = new StringBuffer();
		InputStreamReader isr = new InputStreamReader(is);
		BufferedReader read = new BufferedReader(isr);
		try {
			String line;
			line = read.readLine();
			while (line != null) {
				res.append(line + "<br>");
				line = read.readLine();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != isr) {
					isr.close();
					isr.close();
				}
				if (null != read) {
					read.close();
					read = null;
				}
				if (null != is) {
					is.close();
					is = null;
				}
			} catch (IOException e) {
			}
		}
		return res.toString();
	}

	/***
	 * 截取字符串
	 *
	 * @param start
	 *            从那里开始，0算起
	 * @param num
	 *            截取多少个
	 * @param str
	 *            截取的字符串
	 * @return
	 */
	public static String getSubString(int start, int num, String str) {
		if (str == null) {
			return "";
		}
		int leng = str.length();
		if (start < 0) {
			start = 0;
		}
		if (start > leng) {
			start = leng;
		}
		if (num < 0) {
			num = 1;
		}
		int end = start + num;
		if (end > leng) {
			end = leng;
		}
		return str.substring(start, end);
	}

	/**
	 * 获取当前时间为每年第几周
	 *
	 * @return
	 */
	public static int getWeekOfYear() {
		return getWeekOfYear(new Date());
	}

	/**
	 * 获取当前时间为每年第几周
	 *
	 * @param date
	 * @return
	 */
	public static int getWeekOfYear(Date date) {
		Calendar c = Calendar.getInstance();
		c.setFirstDayOfWeek(Calendar.MONDAY);
		c.setTime(date);
		int week = c.get(Calendar.WEEK_OF_YEAR) - 1;
		week = week == 0 ? 52 : week;
		return week > 0 ? week : 1;
	}

	public static int[] getCurrentDate() {
		int[] dateBundle = new int[3];
		String[] temp = getDataTime("yyyy-MM-dd").split("-");

		for (int i = 0; i < 3; i++) {
			try {
				dateBundle[i] = Integer.parseInt(temp[i]);
			} catch (Exception e) {
				dateBundle[i] = 0;
			}
		}
		return dateBundle;
	}

	/**
	 * 返回当前系统时间
	 */
	public static String getDataTime(String format) {
		SimpleDateFormat df = new SimpleDateFormat(format);
		return df.format(new Date());
	}
	/**
	 * 有效邮箱判断
	 * 
	 * @param inputStr
	 * @return
	 */
	public static boolean isValidEmail(String inputStr) {
		String patternStr = "^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$";
		return inputStr != null && isValidStr(inputStr, patternStr);
	}
	/**
	 * 给指定文字设置高亮
	 * @param tv
	 * @param target 需要高亮的文字
	 * @param color 高亮的颜色
	 */
	public void highlight(TextView tv, String target, int color){
		String temp=tv.getText().toString();
		SpannableStringBuilder spannable = new SpannableStringBuilder(temp);
		CharacterStyle span=null;
		
		Pattern p = Pattern.compile(target);
		Matcher m = p.matcher(temp);
		while (m.find()) {
			span = new ForegroundColorSpan(color);//需要重复！
			spannable.setSpan(span, m.start(), m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		}
		tv.setText(spannable);
	}


	/**
	 * 数字判断
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(String str) {
		if (str.matches("\\d*")) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 获取UTF-8转码后字符串(URL)
	 * 
	 * @param str
	 * @return
	 */
	public static String getUTF8EncodeStr(String str) {
		String codeStr = null;
		try {
			codeStr = URLEncoder.encode(str, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return codeStr;
	}

	/**
	 * 有效身份证判断
	 * 
	 * @param inputStr
	 * @return
	 */
	public static boolean isValidUserCode(String inputStr) {
		String patternStr = "\\d{15}?\\d{18}";
		return isValidStr(inputStr, patternStr);
	}

	/**
	 * 截取字符串
	 * 
	 * @param inputStr
	 * @param maxLength
	 * @return
	 */
	public static String subString(String inputStr, int maxLength) {
		return inputStr.substring(0, maxLength);
	}

	/**
	 * 有效URL判断
	 * 
	 * @param inputStr
	 * @return
	 */
	public static boolean isValidURL(String inputStr) {
		String patternStr = "^((http:[/][/])?w+([.]w+|[/]w*)*)?$";
		return isValidStr(inputStr, patternStr);
	}

	/**
	 * 字符串非空
	 * 
	 * @param inputStr
	 * @return
	 */
	public static boolean isNotNull(String inputStr) {
		if (inputStr == null)
			return false;
		return inputStr.trim().length() > 0;
	}

	/**
	 * 有效国内电话判断
	 * 
	 * @param inputStr
	 * @return
	 */
	public static boolean isValidTel(String inputStr) {
//		String patternStr = "^(([0\\+]\\d{2,3}-)?(0\\d{2,3})-)?(\\d{7,8})(-(\\d{3,}))?$";
		String patternStr = "^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
		if (null == inputStr || "".equals(inputStr)) {
			return false;
		}
		Pattern p = Pattern.compile(patternStr);
		Matcher m = p.matcher(inputStr);
		if (!m.matches()) {
			return false;
		}
		return true;
	}

	/**
	 * 有效国内手机判断
	 * 
	 * @param phone
	 * @return
	 */
	public static boolean isValidPhone(String phone) {
		int length = phone.length();
		if (null == phone || "".equals(phone)) {
			return false;
		}
		Pattern p = Pattern.compile("^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9]))\\d{8}$");
		Matcher m = p.matcher(phone);
		if (length > 11 || !m.matches()) {
			return false;
		}
		return true;
	}

	/**
	 * 过滤文本信息
	 * 
	 * @param inputStr
	 * @return
	 */
	public static String filterText(String inputStr) {
		inputStr = inputStr.replaceAll("<", "&lt");
		inputStr = inputStr.replaceAll(">", "&gt");
		inputStr = inputStr.replaceAll("\"", "&quot;");
		inputStr = inputStr.replaceAll("&", "&amp;");
		return inputStr;
	}

	/**
	 * 内容合法判断
	 * 
	 * @param inputStr
	 * @return
	 */
	public static boolean isErrorInputContent(String inputStr) {
		return inputStr == null || inputStr.length() > 2000 || inputStr.contains("<") || inputStr.contains(">")
				|| inputStr.contains("/") || inputStr.contains("&") || inputStr.contains("!") || inputStr.contains("(")
				|| inputStr.contains(")") || inputStr.contains("=") || inputStr.contains("^") || inputStr.contains("#")
				|| inputStr.contains("@") || inputStr.contains("~") || inputStr.contains("`") || inputStr.contains("|");
	}

	/**
	 * 判断inputStr字符串是否符合patternStr
	 * 
	 * @param inputStr
	 * @return
	 */
	public static boolean isValidStr(String inputStr, String patternStr) {
		boolean isValid = false;
		Pattern p = Pattern.compile(patternStr);
		Matcher m = p.matcher(inputStr);
		if (m.find()) {
			isValid = true;
		} else {
			isValid = false;
		}
		return isValid;
	}

	/**
	 * 去掉手机号码中间的空格和前缀+86
	 * 
	 * @param phoneNum
	 * @return
	 */
	public static String trimPrefixPhone(String phoneNum) {
		String num = phoneNum;
		if (num != null) {
			num = num.replace(" ", "");
			num = num.replace("+86", "");
			num = num.replace("-", "");
			if (num.startsWith("86")) {
				num = num.substring(2);
			}
			// 17951、12593
			if (num.startsWith("17951")) {
				num = num.substring(5);
			}
			if (num.startsWith("12593")) {
				num = num.substring(5);
			}
		}
		return num;
	}

	/**
	 * 解码Unicode编码
	 * 
	 * @param s
	 * @return
	 */
	public static String decodeUnicode(String s) {
		if (s == null) {
			return null;
		}
		while (true) {
			int index = s.indexOf("\\u");
			if (index != -1) {
				String s1 = s.substring(index, index + 6);
				if (s1.matches("\\\\u[0-9A-Fa-f]{4}")) {
					char c = (char) Integer.parseInt(s1.replace("\\u", ""), 16);
					s = s.substring(0, index) + c + s.substring(index + 6);
				}
			} else {
				break;
			}
		}
		return s;
	}
	/**
	 * 密码输入的合法验证
	 * @param password
	 * @return
	 */
	public boolean  isValidatePassword(String password){
		//不支持中文及中文字符
		if (hasChinese(password)) {
			return false;
		}
		return true;
	}

	/**
	 * 是否为中文字符
	 * @param c
	 * @return
	 */
	public static boolean isChinese(char c) {  
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;  
        }  
        return false;  
    }  
  
	/**
	 * 判断字符串是否含有中文或中文字符
	 * @param strName
	 * @return
	 */
    public static boolean hasChinese(String strName) {
        char[] ch = strName.toCharArray();  
        for (int i = 0; i < ch.length; i++) {  
            char c = ch[i];  
            if (isChinese(c) == true) {  
                return true;  
            } 
        }  
        return false;
    }  
    /**
     * 判断是否含有中文
     * 此判断对中文字符判断无效
     * @param str
     * @return
     */
    private static boolean hasChineseChar(String str){
	       boolean temp = false;
	       Pattern p= Pattern.compile("[\u4e00-\u9fa5]");
	       Matcher m=p.matcher(str);
	       if(m.find()){ 
	           temp =  true;
	       }
	       return temp;
	   }

	/**
	 * md5加密
	 * @param info
	 * @return
     */
	public static String getMD5(String info)
	{
		try
		{
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(info.getBytes("UTF-8"));
			byte[] encryption = md5.digest();

			StringBuffer strBuf = new StringBuffer();
			for (int i = 0; i < encryption.length; i++)
			{
				if (Integer.toHexString(0xff & encryption[i]).length() == 1)
				{
					strBuf.append("0").append(Integer.toHexString(0xff & encryption[i]));
				}
				else
				{
					strBuf.append(Integer.toHexString(0xff & encryption[i]));
				}
			}

			return strBuf.toString();
		}
		catch (NoSuchAlgorithmException e)
		{
			return "";
		}
		catch (UnsupportedEncodingException e)
		{
			return "";
		}
	}

	/**
	 * 随机生成6位纯数字短信验证码
	 * @return
     */
	public static String getSmsCode(){
		Random random = new Random();

		String result="";

		for(int i=0;i<6;i++){

			result+=random.nextInt(10);

		}
		return result;
	}

	/**
	 * 随机生成名称
	 *
	 * @return
	 */
	public static String generateName() {
		return UUID.randomUUID().toString() ;
	}
}
